<?php
namespace app\admin\controller;
use think\Controller;
class DataTable extends Controller
// use app\admin\controller\Common;
// class DataTable extends Common
{
    function liveDetail()
    {

        return view();
    }
    
    function liveDetailData()
    {
        $list = db('datatable_live')
                ->alias('dl')
                ->field('dl.*,a.name as admin_name')
                ->join('admin a','a.id=dl.admin_id')
                ->where('dl.is_del',0);
        $count = db('datatable_live')->alias('dl')->field('dl.*,a.name as admin_name')->join('admin a','a.id=dl.admin_id')->where('dl.is_del',0);
        if(input('is_end'))
        {
            $list = $list->where('dl.is_end',input('is_end'));
            $count = $count->where('dl.is_end',input('is_end'));
        }
        else
        {
            $list = $list->where('dl.is_end',0);
            $count = $count->where('dl.is_end',0);
        }
        if(input('keyword'))
        {
            $keyWord = input('keyword');
            $list = $list->where("dl.activity_name LIKE '%$keyWord%' OR dl.activity_address LIKE '%$keyWord%' OR dl.live_contacts_phone LIKE '%$keyWord%'  ");
            $count = $count->where("dl.activity_name LIKE '%$keyWord%' OR dl.activity_address LIKE '%$keyWord%' OR dl.live_contacts_phone LIKE '%$keyWord%'  ");
        }
            
        $page = input()['page']?:1;
        $limit = input()['limit']?:1;
        $list = $list->order('dl.activity_start_time DESC')->page($page,$limit)->select();
        $count = $count->count();
        foreach ($list as $k => $v)
        {
            $list[$k]['activity_date'] = ($v['activity_start_time'] && $v['activity_end_time'])?date('Y-m-d',$v['activity_start_time']).'-'.date('Y-m-d',$v['activity_end_time']):'';
            $list[$k]['activity_time'] = ($v['activity_start_time'] && $v['activity_end_time'])?date('H:i',$v['activity_start_time']).'-'.date('H:i',$v['activity_end_time']):'';
            $list[$k]['add_time'] = date('Y-m-d',$v['add_time']);
            $list[$k]['activity_area'] = $v['province'].$v['city'].$v['county'];
        }
        return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
    }
    
    function liveDetailAdd()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];
            if($data['activity_start_time'])
                $data['activity_start_time'] = strtotime($data['activity_start_time']);
            if($data['activity_end_time'])
                $data['activity_end_time'] = strtotime($data['activity_end_time']);    
            $data['admin_id'] = session('uid','','admin');
            $data['add_time'] = time();
            $sqlStatus = db('datatable_live')->insert($data);
            if($sqlStatus  )
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
        return view();
    }
    
    function liveDetailEdit()
    {
        if(input('id'))
        {
            $info = db('datatable_live')->where('id',input('id'))->find();
            if(session('group_id','','admin') == 2 && $info['admin_id'] != session('uid','','admin') )
            {
                return '非法操作';
            }
            if(request()->isAjax())
            {
                $data = input('post.')['data'];
                if($data['activity_start_time'])
                    $data['activity_start_time'] = strtotime($data['activity_start_time']);
                if($data['activity_end_time'])
                    $data['activity_end_time'] = strtotime($data['activity_end_time']);    
                if(input('post.')['field'] )
                    $data[$_POST['field']] = $_POST['value'];
                $sqlStatus = db('datatable_live')->where('id',input('id'))->update($data);
                return ['msg'=>'操作成功','icon'=>1];
            }
            
            if(in_array(session('group_id','','admin') ,[1,5]))
                $adminList = db('admin')->where('group_id','IN','2,5,1')->order('status DESC,id DESC')->select();
            $this->assign([
                'info'=>$info,
                'adminList'=>$adminList,
            ]);
            return view('live_detail_add');
        }
    }
    

    
    function liveDetailDel()
    {
        if(input('id'))
        {
            $sqlStatus = db('datatable_live')->where('id',input('id'))->setField('is_del', '1');;
            if($sqlStatus)
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
    }
    
    function liveCheck()
    {
        if(input('id'))
        {
            $sqlStatus = db('datatable_live')->where('id',input('id'))->setField('check_status', '1');;
            if($sqlStatus)
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
    }


    /**
     * 直播汇总表
     */
    function liveProcessSummary()
    {
        //获取销售人员 名单
        $admin_id_res = db('datatable_live_process')->field('admin_id,jie_method,transferor')->where('is_del',0)->where('step','in','4,5')->select();
        $admin_id_arr = [];
        $jie_method_arr = [];
        $transferor_arr = [];
        foreach($admin_id_res as $key => $val){
            $admin_id_arr[] = $val['admin_id'];
            if(!empty($val['jie_method'])){
                $jie_method_arr[] = $val['jie_method'];
            }
            if(!empty($val['transferor'])){
                $transferor_arr[] = $val['transferor'];
            }
        }

        $admin_id_arr = array_flip(array_flip($admin_id_arr));
        $admin_id_str = implode(',',$admin_id_arr);
        $adminList = db('admin')->where('status',1)->where('group_id',2)->where('id','in',$admin_id_str)->field('id,name')->select();

        //获取 结算类型 jie_method
        $jie_method_arr = array_flip(array_flip($jie_method_arr));
        //获取 结算人 transferor
        $transferor_arr = array_flip(array_flip($transferor_arr));

        if(input()['limit'])
        {
            $list = db('datatable_live_process')
                ->alias('dl')
                ->field('dl.*,a.name as admin_name')
                ->join('admin a','a.id=dl.admin_id')
                ->where('dl.is_del',0);
            $count = db('datatable_live_process')->alias('dl')->field('dl.*,a.name as admin_name')->join('admin a','a.id=dl.admin_id')->where('dl.is_del',0);
            $adminId = session('uid','','admin');

            //是否结算
            if(input('step')!='')
            {
                $list = $list->where('dl.step','IN',input('step'));
                $count = $count->where('dl.step','IN',input('step'));
            }
            //销售员
            if(input('admin_id'))
            {
                $admin_id = input('admin_id');
                $list = $list->where('a.id','eq',$admin_id);
                $count = $count->where('a.id','eq',$admin_id);
            }
            //直播日期 开始时间
            if(input('start_date'))
            {
                $start_date = strtotime(input('start_date'));
                $list = $list->where('dl.activity_start_time','>=',$start_date);
                $count = $count->where('dl.activity_start_time','>=',$start_date);
            }
            //直播日期 结束时间
            if(input('end_date'))
            {
                $end_date = strtotime(input('end_date'));
                $list = $list->where('dl.activity_end_time','<=',$end_date);
                $count = $count->where('dl.activity_end_time','<=',$end_date);
            }
            //结算类型
            if(input('jie_method'))
            {
                $jie_method = input('jie_method');
                $list = $list->where('dl.jie_method','eq',$jie_method);
                $count = $count->where('dl.jie_method','eq',$jie_method);
            }
            //结算人
            if(input('transferor'))
            {
                $transferor = input('transferor');
                $list = $list->where('dl.transferor','eq',$transferor);
                $count = $count->where('dl.transferor','eq',$transferor);
            }
//            if(input('keyword'))
//            {
//                $keyWord = input('keyword');
//                $list = $list->where('dl.activity_name|dl.activity_address|dl.liveer_phone|dl.city|dl.county|dl.province|a.name','LIKE',"%$keyWord%");
//                $count = $count->where('dl.activity_name|dl.activity_address|dl.liveer_phone|dl.city|dl.county|dl.province|a.name','LIKE',"%$keyWord%");
//            }
            if(session('group_id','','admin') == 5 && $adminId != 12)
            {
                $manager = db('admin')->field('name,id,group_members,group_name')->where('id',$adminId)->find();
                $groupMembers = $manager['group_members']?$manager['id'].','.$manager['group_members']:$manager['id'];
                $list = $list->where('dl.admin_id','IN',$groupMembers );
                $count = $count->where('dl.admin_id','IN',$groupMembers );
            }
            else if(session('group_id','','admin') == 2)
            {
                $list = $list->where('dl.admin_id',$adminId);
                $count = $count->where('dl.admin_id','IN',$groupMembers );
            }
//            if(session('uid','','admin') == 1)
//            {
//                //$list = $list->where('status','>',0);
//            }

            $page = input()['page']?:1;
            $limit = input()['limit']?:1;
            $list = $list->order('dl.step ASC,dl.activity_start_time DESC')->page($page,$limit)->select();
            $count = $count->count();
            $sum = [];
            $sum['admin_name'] = "——";
            $sum['live_id'] = "汇总";
            $sum['activity_name'] = "——";
            foreach ($list as $k => $v)
            {
                $list[$k]['activity_date'] = ($v['activity_start_time'] && $v['activity_end_time'])?date('Y-m-d',$v['activity_start_time']).'-'.date('Y-m-d',$v['activity_end_time']):'';
                $list[$k]['activity_time'] = ($v['activity_start_time'] && $v['activity_end_time'])?date('H:i',$v['activity_start_time']).'-'.date('H:i',$v['activity_end_time']):'';
                $list[$k]['add_time'] = date('Y-m-d',$v['add_time']);
                $list[$k]['activity_area'] = $v['province'].$v['city'].$v['county'];
                $sum['liveer_price'] += $v['liveer_price'];
                $sum['jie_price'] += $v['jie_price'];
            }
            array_unshift($list,$sum);

            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            $this->assign([
                'adminList'=>$adminList,
                'jieMethodList'=>$jie_method_arr,
                'transferorList'=>$transferor_arr,
            ]);
            return view();
    }



    
    function liveProcess()
    {
        if(input()['limit'])
        {
            $list = db('datatable_live_process')
                    ->alias('dl')
                    ->field('dl.*,a.name as admin_name')
                    ->join('admin a','a.id=dl.admin_id')
                    ->where('dl.is_del',0);
            $count = db('datatable_live_process')->alias('dl')->field('dl.*,a.name as admin_name')->join('admin a','a.id=dl.admin_id')->where('dl.is_del',0);
            $adminId = session('uid','','admin');
            if(input('step')!='')
            {
                $list = $list->where('dl.step','IN',input('step'));
                $count = $count->where('dl.step','IN',input('step'));
            }
            else
            {
                //$list = $list->where('dl.step','IN',input('step'));
                //$count = $count->where('dl.step','IN',input('step'));
            }
            if(input('start_date'))
            {
                $start_date = strtotime(input('start_date'));
                $list = $list->where('dl.activity_start_time','>=',$start_date);
                $count = $count->where('dl.activity_start_time','>=',$start_date);
            }
            if(input('end_date'))
            {
                $end_date = strtotime(input('end_date'));
                $list = $list->where('dl.activity_end_time','<=',$end_date);
                $count = $count->where('dl.activity_end_time','<=',$end_date);
            }
            if(input('keyword'))
            {
                $keyWord = input('keyword');
                $list = $list->where('dl.activity_name|dl.activity_address|dl.liveer_phone|dl.city|dl.county|dl.province|a.name','LIKE',"%$keyWord%");
                $count = $count->where('dl.activity_name|dl.activity_address|dl.liveer_phone|dl.city|dl.county|dl.province|a.name','LIKE',"%$keyWord%");
            }
            if(session('group_id','','admin') == 5 && $adminId != 12)
            {
                $manager = db('admin')->field('name,id,group_members,group_name')->where('id',$adminId)->find();
                $groupMembers = $manager['group_members']?$manager['id'].','.$manager['group_members']:$manager['id'];
                $list = $list->where('dl.admin_id','IN',$groupMembers );
                $count = $count->where('dl.admin_id','IN',$groupMembers );
            }
            else if(session('group_id','','admin') == 2)
            {
                $list = $list->where('dl.admin_id',$adminId);
                $count = $count->where('dl.admin_id','IN',$groupMembers );
            }
            if(session('uid','','admin') == 1)
            {
                //$list = $list->where('status','>',0);
            }
            
            $page = input()['page']?:1;
            $limit = input()['limit']?:1;
            $list = $list->order('dl.step ASC,dl.activity_start_time DESC')->page($page,$limit)->select();
            $count = $count->count();
            foreach ($list as $k => $v)
            {
                $list[$k]['activity_date'] = ($v['activity_start_time'] && $v['activity_end_time'])?date('Y-m-d',$v['activity_start_time']).'-'.date('Y-m-d',$v['activity_end_time']):'';
                $list[$k]['activity_time'] = ($v['activity_start_time'] && $v['activity_end_time'])?date('H:i',$v['activity_start_time']).'-'.date('H:i',$v['activity_end_time']):'';
                $list[$k]['add_time'] = date('Y-m-d',$v['add_time']);
                $list[$k]['activity_area'] = $v['province'].$v['city'].$v['county'];
            }
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function liveProcessZx()
    {
        if(!input('keyword') )
        {
            $tagList = db('datatable_live_process')->field('province as tag,count(province) as count')->where('is_del',0)->where('step','in','0,1,2,3')->where('activity_end_time','>',time())->group('province having(count(province)>1)')->select();
        }
        else
        {
            $tagList = db('datatable_live_process')->field('city as tag,count(city) as count')->where('province',input('keyword'))->where('is_del',0)->where('step','in','0,1,2,3')->where('activity_end_time','>',time())->group('city having(count(city)>1)')->select();
        }

        
        $this->assign(['tagList'=>$tagList]);
        return view();
    }
    
    function liveProcessJs()
    {
//        $start_date = input('start_date');
//        $end_date = input('end_date');
        return view();
    }
    
    function liveProcessAdd()
    {
        if(request()->isAjax())
        {
            $data = input('post.');  
            if(!$data['admin_id'] && !$data['id'])
            {
                $data['admin_id'] = session('uid','','admin');
            }
            if(!$data['liveer_name'] && !$data['id'])
            {
                $data['step'] = 0;
            }
            if($data['need_recommend'] && !$data['id'])
            {
                $data['step'] = 2;
            }
            if($data['rate_1'] || $data['rate_2'] || $data['rate_3'])
            {
                $data['step'] = 4;
                $data['rate_time'] = time();
            }
            if($data['jie_method'] && $data['transferor'])
            {
                $data['step'] = 5;
                $data['jie_time'] = time();
            }
            if($data['activity_start_time'])
                $data['activity_start_time'] = strtotime($data['activity_start_time']);
            if($data['activity_end_time'])
                $data['activity_end_time'] = strtotime($data['activity_end_time']);  
            $sqlStatus = 1;
            if(!input('id'))
            {
                $data['add_time'] = time();
                $sqlStatus = db('datatable_live_process')->insert($data);
            }
            else
                db('datatable_live_process')->where('id',input('id'))->update($data);
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else
        {
            if(input('id'))
                $this->assign('data',db('datatable_live_process')->where('id',input('id'))->find());
            if(in_array(session('group_id','','admin') ,[1,5]))
                $this->assign('adminList',db('admin')->where('group_id','IN','2,5,1')->order('status DESC,id DESC')->select());
            
            return view();
        }
    }
    
    function liveProcessLiveer()
    {
        if(request()->isAjax())
        {
            $data = input('post.');  
            $sqlStatus = 1;
            if($data['need_recommend'] == 1)
            {
                $dataa = db('datatable_live_process')->where('id',$data['id'])->find();
                $data['liveer_name'] = $dataa['recommend_liveer_name'];
                $data['liveer_phone'] = $dataa['recommend_liveer_phone'];
                $data['liveer_price'] = $dataa['recommend_liveer_price'];
                $data['liveer_bill'] = $dataa['recommend_liveer_bill'];
                $data['step'] = 3;
            }
            else if($data['need_recommend'] == -1)
            {
                $data['step'] = 2;
            }
            if($data['id'])
                db('datatable_live_process')->where('id',$data['id'])->update($data);
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else
        {
            if(input('id'))
                $this->assign('data',db('datatable_live_process')->where('id',input('id'))->find());

            return view();
        }
    }
    
    
    function liveProcessView()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];  
            $data['admin_id'] = session('uid','','admin');
            $sqlStatus = 1;
            if(!$data['id'])
            {
                $data['add_time'] = time();
                $sqlStatus = db('datatable_live_process')->insert($data);
            }
            else
                db('datatable_live_process')->where('id',$data['id'])->update($data);
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else
        {
            if(input('id'))
                $this->assign('data',db('datatable_live_process')->where('id',input('id'))->find());

            return view();
        }
    }
    
    function liveDetailEditQuick()
    {
        if(session('uid','','admin') == 1)
        {
            $id = input()['id'];
            if(input('field'))
            {
                $field = input()['field'];
                $value = input()['value'];
                $sqlStatus = db('datatable_live_process')->where('id',$id)->update([ $field=>$value ]);
            }
            else if(input('post.'))
            {
                $data = input('post.');
                $sqlStatus = db('datatable_live_process')->where('id',$id)->update($data);
            }
        }
        return ['msg'=>'操作成功','icon'=>1,'code'=>1];
    }
    
    function liveProcessRate()
    {
        if(input('id'))
            $this->assign('data',db('datatable_live_process')->where('id',input('id'))->find());

        return view();
    }
    
    function liveProcessJie()
    {
        if(input('id'))
            $this->assign('data',db('datatable_live_process')->where('id',input('id'))->find());

        return view();
    }
    
    function liveProcessCancel()
    {
        if(input('id'))
        {
            $sqlStatus = db('datatable_live_process')->where('id',input('id'))->setField('step', '-1');
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
    }
    
    function liveProcessDel()
    {
        if(input('id'))
        {
            $sqlStatus = db('datatable_live_process')->where('id',input('id'))->setField('step', '-2');
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
    }
    
    public function upload(){
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(JIESUANIMG);
        $data = array();  //定义一个返回的数组
        if($info){
            $reubfo['code']= 1;
            $reubfo['savename'] = str_replace("\\","/",$info->getSaveName());
        }else{
            // 上传失败获取错误信息
            $reubfo['code']= 0;
            $reubfo['err'] = $file->getError();
        } 
        return json_encode($reubfo);
    }
    
    function liveBook()
    {
        if(input()['limit'])
        {
            $page = input()['page'];
            $limit = input()['limit'];
            $keyWord = input()['keyword'];
            $list = db('datatable_livebook')->where('name|phone|province|city|county|address|type','LIKE',"%$keyWord%")->where('is_del',0)->page($page,$limit)->select();
            $count = db('datatable_livebook')->where('name|phone|province|city|county|address|type','LIKE',"%$keyWord%")->where('is_del',0)->page($page,$limit)->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function liveBookAdd()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];  
            $data['admin_id'] = session('uid','','admin');
            $sqlStatus = 1;
            if(!$data['id'])
            {
                $data['add_time'] = time();
                $sqlStatus = db('datatable_livebook')->insert($data);
            }
            else
                db('datatable_livebook')->where('id',$data['id'])->update($data);
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else
        {
            if(input('id'))
                $this->assign(['data'=>db('datatable_livebook')->where('id',input('id'))->find()]);
            return view();
        }
        
    }
    
    function liveBookDel()
    {
        if(input('id'))
        {
            $sqlStatus = db('datatable_livebook')->where('id',$data['id']);
            if(session('group_id','','admin') != 1)
            {
                $sqlStatus = $sqlStatus->where('admin_id',session('uid','','admin_id'));
            }
            $sqlStatus = $sqlStatus->update(['is_del'=>1]);
        }
    }
    
    function xbjb()
    {
        if(input()['page'])
        {
            $list = db('other_xbjb');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('name','LIKE',"%".input()['keyword']."%");
            $list = $list->order('vote_id DESC')->select();
            $count = db('other_xbjb')->where('name','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function xbjbCategory()
    {
        if(input()['page'])
        {
            $list = db('other_xbjb_category');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('name','LIKE',"%".input()['keyword']."%");
            $list = $list->order('category_id DESC,id DESC')->select();
            $count = db('other_xbjb_category')->where('name','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function ssxg()
    {
        if(input()['page'])
        {
            $list = db('other_ssxg');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('name','LIKE',"%".input()['keyword']."%");
            $list = $list->order('id DESC')->select();
            $count = db('other_ssxg')->where('name','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function ssxgCategory()
    {
        if(input()['page'])
        {
            $list = db('other_ssxg_category');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('name','LIKE',"%".input()['keyword']."%");
            $list = $list->order('category_id DESC,id DESC')->select();
            $count = db('other_ssxg_category')->where('name','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function jczb()
    {
        if(input()['page'])
        {
            $list = db('other_jczb');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('title','LIKE',"%".input()['keyword']."%");
            $list = $list->order('camera_id DESC')->select();
            $count = db('other_jczb')->where('title','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function jzzb()
    {
        if(input()['page'])
        {
            $list = db('other_jzzb');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('title','LIKE',"%".input()['keyword']."%");
            $list = $list->order('voteid DESC')->select();
            $count = db('other_jzzb')->where('title','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function dailySpend()
    {
        if(input()['page'])
        {
            $list = db('datatable_daily_spend');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('detail','LIKE',"%".input()['keyword']."%");
            $list = $list->order('spend_time DESC')->select();
            foreach($list as $k=>$v)
            {
                $list[$k]['admin_name'] = $v['admin_id']?idToAdminname($v['admin_id']):'';
                $list[$k]['spend_time'] = date('Y-m-d',$list[$k]['spend_time']);
            }
            $count = db('datatable_daily_spend')->where('detail','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function dailySpendAdd()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];  
            $data['add_admin_id'] = session('uid','','admin');
            $data['spend_time'] = strtotime($data['spend_time']);
            $sqlStatus = 1;
            if(!$data['id'])
            {
                $data['add_time'] = time();
                $sqlStatus = db('datatable_daily_spend')->insert($data);
            }
            else
                db('datatable_daily_spend')->where('id',$data['id'])->update($data);
            return $sqlStatus?['msg'=>'操作成功','icon'=>1]:['msg'=>'操作失败','icon'=>2];
        }
        else
        {
            if(input('id'))
                $this->assign('data',db('datatable_daily_spend')->where('id',input('id'))->find());
            $this->assign('adminList',db('admin')->where('status',1)->where('group_id','IN','5,2')->order('id DESC')->select());
            return view();
        }
    }
    
    function departStaffWeek()
    {
        if(input()['page'])
        {
            $list = db('datatable_daily_spend');
            if(input()['limit'])
                $list = $list->page(input()['page'],input()['limit']);
            if(input()['keyword'])
                $list = $list->where('detail','LIKE',"%".input()['keyword']."%");
            $list = $list->order('spend_time DESC')->select();
            foreach($list as $k=>$v)
            {
                $list[$k]['admin_name'] = $v['admin_id']?idToAdminname($v['admin_id']):'';
                $list[$k]['spend_time'] = date('Y-m-d',$list[$k]['spend_time']);
            }
            $count = db('datatable_daily_spend')->where('detail','LIKE',"%".input()['keyword']."%")->count();
            return ['code'=>0,'count'=>$count,'data'=>$list,'msg'=>''];
        }
        else
            return view();
    }
    
    function dataStatForMonth()
    {
        $year = date('Y');
        $month = input()['month']?:date('m');
        if(input()['page'])
        {
            $startTime = strtotime($year.'-'.$month.'-01');
            $endTime = strtotime(date('Y-m-t',$startTime) )+86399;
            for($i = 1; $i<=4 ; $i++)
            {
                $list[$i] = db('performance')->alias('c')->field('sum(c.salesman_final_performance) as s,count(c.id) as c')->join('admin a','a.id=c.admin_id')->where('c.end_date','>=',strtotime('2022-'.$month.'-01') )->where('c.end_date','<=',strtotime(date('Y-m-t',$startTime) )+86399 )->where('a.department_id',$i)->find();
                $list[$i]['count'] = get_depart_count($i);
                $list[$i]['depart_name'] = get_depart_name($i);
                $list[$i]['avg'] = round($list[$i]['s'] / $list[$i]['count'] , 2);
                $list[$i]['s'] = round($list[$i]['s'] , 2);
                $list[$i]['qdl'] = db('client')->alias('c')->join('admin a','a.id=c.xaid')->where('c.qiandan_time','>=',strtotime('2022-'.$month.'-01') )->where('c.qiandan_time','<=',strtotime(date('Y-m-t',$startTime) )+86399 )->where('a.department_id',$i)->value('count(c.id) as c');
                $list[$i]['yms'] = db('active_page_log')->alias('c')->join('admin a','a.id=c.to_admin_id')->where('c.complete_time','>=',strtotime('2022-'.$month.'-01') )->where('c.complete_time','<=',strtotime(date('Y-m-t',$startTime) )+86399 )->where('a.department_id',$i)->value('count(c.id) as c');;
            }
            return ['code'=>0,'count'=>4,'data'=>$list,'msg'=>''];
        }
        $this->assign([
            'month'=>$month,
            'year'=>$year,
        ]);
        return view();
    }
    
    function departClientStartForMonth()
    {
        $year = date('Y');
        $month = input()['month']?:date('m');
        if(input()['page'])
        {
            $startTime = strtotime($year.'-'.$month.'-01');
            $endTime = strtotime(date('Y-m-t',$startTime) )+86399;
            for($i = 1; $i<=4 ; $i++)
            {
                $list[$i] = db('datatable_client_start_month')->alias('c')->field('sum(c.count) as s,group_concat(live_ids) as live_ids')->join('admin a','a.id=c.admin_id')->where('c.month_date',strtotime('2022-'.$month.'-01') )->where('a.department_id',$i)->find();
                $list[$i]['count'] = get_depart_count($i);
                $list[$i]['depart_name'] = get_depart_name($i);
                $list[$i]['avg'] = round($list[$i]['s'] / $list[$i]['count'] , 2);
                $list[$i]['yqd'] = 0; 
                foreach (explode(',',$list[$i]['live_ids']) as $k=>$v)
                {
                    if(get_vote_start_at($v) && get_vote_start_at($v) < time() )
                        $list[$i]['yqd'] ++;
                }
                $list[$i]['wqd'] = $list[$i]['count'] - $list[$i]['yqd'];
            }
            return ['code'=>0,'count'=>4,'data'=>$list,'msg'=>''];
        }
        $this->assign([
            'month'=>$month,
            'year'=>$year,
        ]);
        return view();
    }
    
    function departStaffDataForWeek()
    {
        $adminId = session('uid','','admin');
        if(input()['page'])
        {
            $startTime = strtotime($year.'-'.$month.'-01');
            $endTime = strtotime(date('Y-m-t',$startTime) )+86399;
            for($i = 1; $i<=4 ; $i++)
            {
                $list[$i] = db('datatable_client_start_month')->alias('c')->field('sum(c.count) as s,group_concat(live_ids) as live_ids')->join('admin a','a.id=c.admin_id')->where('c.month_date',strtotime('2022-'.$month.'-01') )->where('a.department_id',$i)->find();
                $list[$i]['count'] = get_depart_count($i);
                $list[$i]['depart_name'] = get_depart_name($i);
                $list[$i]['avg'] = round($list[$i]['s'] / $list[$i]['count'] , 2);
                $list[$i]['yqd'] = 0; 
                foreach (explode(',',$list[$i]['live_ids']) as $k=>$v)
                {
                    if(get_vote_start_at($v) && get_vote_start_at($v) < time() )
                        $list[$i]['yqd'] ++;
                }
                $list[$i]['wqd'] = $list[$i]['count'] - $list[$i]['yqd'];
            }
            return ['code'=>0,'count'=>4,'data'=>$list,'msg'=>''];
        }
        
        $weekList = db('datatable_depart_staff_week')->select();
    
        if(session('group_id','','admin') == 5)
        {
            $manager = db('admin')->field('name,id,group_members,group_name')->where('id',$adminId)->find();
            $groupMembers = $manager['group_members']?$manager['id'].','.$manager['group_members']:$manager['id'];
            $list = $list->where('p.admin_id','IN',$groupMembers );
        }
        if(session('group_id','','admin') == 2)
        {
            $list = $list->where('p.admin_id',$adminId);
        }
            
        $this->assign([
            'month'=>$month,
            'year'=>$year,
        ]);
        return view();
    }
    
    
    
    function departStaffDataAdd()
    {
        if(input('post.'))
        {
            if(input('type') == 1)
            {
                $data = input('post.');
                $data['admin_id'] = session('uid','','admin');
                if($data['id'])
                {
                    db('datatable_depart_staff_week')->where('id',$data['id'])->update($data);
                }
                else
                {
                    db('datatable_depart_staff_week')->insert($data);
                }
            }
            else if(input('type') == 2)
            {
                $data = input('post.');
                $monthDate = $data['month_date'];
                $adminId = session('uid','','admin');
                foreach ($data['client_id'] as $k=>$v)
                {
                    if($v)
                    {
                        $idata['month_date'] = $monthDate;
                        $idata['admin_id'] = $adminId;
                        $idata['client_id'] = $v;
                        $idata['count'] = $data['count'][$k];
                        $idata['live_ids'] = $data['live_ids'][$k];
                        $checkId = db('datatable_client_start_month')->where('month_date',$monthDate)->where('client_id',$v)->where('admin_id',$adminId)->value('id');
                        if($checkId)
                        {
                            db('datatable_client_start_month')->where('id',$checkId)->update($idata);
                        }
                        else
                        {
                            db('datatable_client_start_month')->insert($idata);
                        }
                    }
                }
                
            }
            header('location:'.$_SERVER['HTTP_REFERER']);
        }
        else
        {
            $clientList = db('client')->where('status',4);
            if(session('group_id','','admin') != 1 && session('group_id','','admin') != 8)
                $clientList = $clientList->where('xaid',session('uid','','admin'));
            $clientList = $clientList->order('qiandan_time DESC')->select();
            
            $date1 = input('date1')?input('date1'):strtotime(date('Y-m-d',strtotime('last week')));
            $date2 = input('date2')?input('date2'):strtotime(date('Y-m',strtotime('this month')));
            if($date1)
            {
                $data = db('datatable_depart_staff_week')->where('admin_id',session('uid','','admin') )->where('week_date',$date1)->find();
            }
            if($date2)
            {
                $canStartCount = db('datatable_client_start_month')->where('admin_id',session('uid','','admin') )->where('month_date',$date2)->select();
            }
            
            $this->assign([
                'week_dates'=>[strtotime(date('Y-m-d',strtotime('last week'))),strtotime(date('Y-m-d',strtotime('this week')))],
                'month_dates'=>[ strtotime(date('Y-m',strtotime('this month'))),strtotime(date('Y-m',strtotime('last month'))),],
                'clientList'=>$clientList,
                'data'=>$data,
                'can_start_count'=>$canStartCount
            ]);
            return view();
        }

    }
    
    function matchSpend()
    {
        return view();
    }
    
    function moneyDaybook()
    {
        return view();
    }
    
    
}